#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    layoutMainWindow();
    //humiture = new PAGEHUMITURE;
    fhwidget=new Widget;
    newFunctionPage("  温湿度测试  ",fhwidget);

    connect(fhwidget,SIGNAL(cmdSend()),this,SLOT(sendCmd()));

    linkToHardware = new serialConnection;

    connect(linkToHardware->serPort,SIGNAL(readyRead()),this,SLOT(readData()));
}

void MainWindow::layoutMainWindow()
{
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);

    QPalette p = palette();
   // p.setColor(QPalette::Window,QColor(200,200,200));
   p.setColor(QPalette::Window,QColor(180,180,180));
    //  p.setColor(QPalette::Window,QColor(110,123,139));
    setPalette(p);

    QFile file(":/image/res/this.css");

    file.open(QFile::ReadOnly);

    QString qss = QLatin1String(file.readAll());

    qApp->setStyleSheet(qss);

    // basic layout of the main window
    QVBoxLayout *layoutMain = new QVBoxLayout;

    // headerBar layout
    QHBoxLayout *layoutHeaderBar = new QHBoxLayout;
    layoutHeaderBar->setContentsMargins(0,0,0,0);

    QPushButton *labBeforeTitle = new  QPushButton;
    labBeforeTitle->setFixedSize(100,39);
    labBeforeTitle->setStyleSheet("background:url(:/image/res/icon1.png)  no-repeat center;border:0px;");
    connect(labBeforeTitle,SIGNAL(clicked()),this,SLOT(set_debug()));

    QFont ft;
    ft.setBold(true);
    ft.setPixelSize(25);
    QLabel *labTitle = new QLabel("负荷箱校验装置");
    labTitle->setFixedHeight(32);
    labTitle->setFont(ft);
    labTitle->setStyleSheet("color:#666;");

    btnScreenShot = new QPushButton;
    btnScreenShot->setFixedSize(32,32);
    btnScreenShot->setStyleSheet("background:url(:/image/res/icon_screenshot.png)  no-repeat center;border:0px;");
    btnScreenShot->clearFocus();

    state=new QLabel(tr("调试状态..."));
    statetime=new QTimer;
    connect(statetime,SIGNAL(timeout()),this,SLOT(time_over()));
    state->hide();

    QPushButton *btnClose = new QPushButton;
    btnClose->setFixedSize(32,32);
    btnClose->setStyleSheet("background:url(:/image/res/icon_close.png)  no-repeat center;border:0px;");
    btnScreenShot->clearFocus();

    QPushButton *btnUpdata = new QPushButton;
    btnUpdata->setFixedSize(32,32);
    btnUpdata->setStyleSheet("background:url(:/image/res/upload_32px_2.png)  no-repeat center;border:0px;");
   // btnUpdata->setStyleSheet("background:url(:/image/res/up_32px_1.png)  no-repeat center;border:0px;");
    btnScreenShot->clearFocus();

    connect(btnClose, SIGNAL(clicked()),this,SLOT(appQuit()));
    connect(btnScreenShot, SIGNAL(clicked()),this,SLOT(takePhoto()));
    connect(btnUpdata,SIGNAL(clicked()),this,SLOT(toUpdate()));


    layoutHeaderBar->addSpacing(10);
    layoutHeaderBar->addWidget(labBeforeTitle);
    layoutHeaderBar->addWidget(labTitle);
    layoutHeaderBar->addWidget(state);
    layoutHeaderBar->addStretch(1);
    layoutHeaderBar->addWidget(btnUpdata);
    layoutHeaderBar->addWidget(btnScreenShot);
    //layoutHeaderBar->addSpacing(5);
    layoutHeaderBar->addWidget(btnClose);
    layoutHeaderBar->addSpacing(10);

    // main area
    QWidget *widgetMainContent = new QWidget;
    widgetMainContent->setFixedSize(1024,555);
    //widgetMainContent->setStyleSheet(".QWidget{background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 white, stop:0.05 #bbb, stop:0.97 #aaa, stop:1 #555);margin:0px;border:0px;border-radius:15px;padding:0px;}");
    //widgetMainContent->setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 white, stop:0.02 #ccc, stop:0.98 #bbb, stop:1 #666);");

    // menu bar layout
    QWidget *widgetMenuBar = new QWidget;

    layoutMenuBar = new QHBoxLayout;
//    QLabel *blankLabel = new QLabel("");
//    blankLabel->setFixedWidth(35);
//    blankLabel->setStyleSheet("background:url(:/image/res/click.png)  no-repeat center;border:0px;");
 //   layoutMenuBar->addWidget(blankLabel);
    layoutMenuBar->addStretch(1);
    layoutMenuBar->setSpacing(10);
    layoutMenuBar->setContentsMargins(15,10,100,8);

    widgetMenuBar->setLayout(layoutMenuBar);
    widgetMenuBar->setFixedHeight(35);
    // widgetMenuBar->setStyleSheet(".QWidget{background-color:qcolor(220,200,20,150);}");
    widgetMenuBar->setStyleSheet(".QWidget{background-color:gray;}");

    ft.setPixelSize(17);
    ft.setBold(false);

    // the stacked widget
    stackedPage = new QStackedWidget;
    stackedPage->setFixedSize(1000,480);
    // stackedPage->setStyleSheet("background-color:#ffffff");

    listFunctionPage = new QStringList;

    QVBoxLayout *layoutStackedPage = new QVBoxLayout;
    layoutStackedPage->addWidget(widgetMenuBar);
    layoutStackedPage->addSpacing(8);
    layoutStackedPage->addWidget(stackedPage);
    layoutStackedPage->addStretch(1);
    layoutStackedPage->setContentsMargins(0,10,0,0);

    widgetMainContent->setLayout(layoutStackedPage);

    layoutMain->addLayout(layoutHeaderBar);
    layoutMain->addWidget(widgetMainContent);
    layoutMain->addStretch(1);

    // the centralWidget
    QWidget *widgetMain = new QWidget;
    widgetMain->setFixedSize(1024,600);

    // move window to center of sceen
    QDesktopWidget deskWindow;
    int deskWidth = deskWindow.width();
    int deskHeight = deskWindow.height();
    this->move(deskWidth / 2 - widgetMain->width() / 2, deskHeight / 2 - widgetMain->height() / 2);

    widgetMain->setLayout(layoutMain);
    this->setCentralWidget(widgetMain);

    layoutMain->setContentsMargins(0,4,0,4);
}

void MainWindow::newFunctionPage(QString name, QWidget* functionPage)
{
   // addButtonToMenu(name);

    stackedPage->addWidget(functionPage);

    listFunctionPage->append(name);

    switchFunctionPage(name);
}

void MainWindow::addButtonToMenu(QString name)
{
    updateMenu(Add, name,0);
}

void MainWindow::toggleButtonInMenu(int pageIndex)
{
    updateMenu(Show, NULL, pageIndex);
}

void MainWindow::updateMenu(menuOperation opt, QString name,int pageIndex)
{
    static QVector <myButton*> listButton;

    if(opt == Add)
    {
        QFont ft;
        ft.setPixelSize(20);

        myButton *btnFunction = new myButton;
        btnFunction->setText(name);
        btnFunction->setFont(ft);
        btnFunction->setMargin(2);

        layoutMenuBar->insertWidget(1,btnFunction);

        listButton.append(btnFunction);

        connect(btnFunction,SIGNAL(clicked(QString)),this,SLOT(switchFunctionPage(QString)));
    }
    else if(opt == Show)
    {
        for(int i = 0; i < listButton.size();i++)
        {
            if(i == pageIndex)
            {
                listButton[i]->highLight(true);
            }
            else
            {
                listButton[i]->highLight(false);
            }
        }
    }
}

void MainWindow::switchFunctionPage(QString name)
{
    int pageIndex = listFunctionPage->indexOf(name);
    stackedPage->setCurrentIndex(pageIndex);

    toggleButtonInMenu(pageIndex);

    btnScreenShot->setFocus();
}

void MainWindow::takePhoto()
{
    QPixmap originalPixmap = QPixmap::grabWindow(QApplication::desktop()->winId());

    QString format = "png";

    QDateTime time = QDateTime::currentDateTime();

    QString str = time.toString("yyyy-MM-dd-hh-mm-ss");

    QString filename = str + ".png";

#ifndef i386
    QDir toDir("/udisk/");
#else
    QDir toDir("./udisk");
#endif

    if (!toDir.exists())
    {
        QString s=tr("U 盘未插入或不支持该 U 盘，请重试！");
        QMessageBox::information(NULL,tr("错误"),s);
        return;
    }

    if(toDir.exists("screenshot"))
    {
         qDebug() << "screenshot/ is existed!";
//         toDir.setFilter(QDir::Files);
//         toDir.setSorting(QDir::Time);

//         QFileInfoList list = toDir.entryInfoList();

//         int i = 0;
//         for(i=0 ; i<list.size(); i++)
//         {
//             if(i > 30)
//             {
//                 QFileInfo fileInfo = list.at(i);
//                 toDir.remove( fileInfo.fileName() );

//                 qDebug() << "Deleted file: "<<fileInfo.fileName();
//             }
//         }
    }
    else
    {
         qDebug() << "mkdir screenshot";
         toDir.mkdir("screenshot");
    }

     toDir.setPath(toDir.absolutePath()+"/screenshot");
     qDebug() <<"image . path():" <<toDir.absolutePath();
     if(! toDir.exists())
     {
         QString s=tr("读写 U 盘错误！");
         QMessageBox::information(NULL,tr("错误"),s);
         return;
     }

     filename = toDir.absolutePath()+ "/" + filename;

     if (!filename.isEmpty())
     {
         originalPixmap.save(filename, format.toAscii());

//         if(!QFile::copy(sfile, "./screenshot"))
//         {
//            QString s=tr("截图未保存到 U 盘！");
//            QMessageBox::information(NULL,tr("错误"),s);
//         }
//         else
//         {
             QString s=tr("截图已保存到 U 盘！");
//             humiture->labInfo->setText(s);
//             humiture->widgetInfo->show();
             QTimer::singleShot(1000, this, SLOT(widgetInfoHide())); //虚框隐藏
//         }
     }
}

void MainWindow::readData()
{
    static QByteArray getData;

    QByteArray cmd = "";

    int length=0;

    getData.append(linkToHardware->serPort->readAll());


FIND_CMD:
    cmd = "";

    qDebug()<<"The data we received is:"<<getData.toHex();

    if( getData.length() < 2)
    {
        return;
    }

    while( 0x40 != (unsigned char)getData[0])
    {
        getData = getData.mid(1);

        if(getData.length() < 2)
            return;
    }

    length = getData[1]; //将长度提取出来
    qDebug()<<"length:"<<length;

    if( getData.length() < length + 2) return;

    cmd = getData.left(length + 2);

    qDebug()<<"find a cmd:"<<cmd.toHex();

    //humiture->recvResult(cmd);

    getData = getData.mid(length + 2);

    goto FIND_CMD;
}


void MainWindow::sendData(QByteArray sendBuf)
{
    linkToHardware->serPort->write(sendBuf);

    qDebug()<<"we send: "<<sendBuf.toHex();
}


void MainWindow::sendCmd()
{
    if(!linkToHardware->serPort->isOpen())
    {
        qDebug()<<"main, sendCmd: no connection to hardware!";

        //QWidget* theSender = (QWidget*)sender();

        QByteArray errStr;
        errStr[0]=0xff;

        if(linkToHardware->errno == 0)
        {
            errStr.append("找不到 USB 串口！");
        }
        else
        {
            errStr.append(linkToHardware->serPort->errorString());
        }

//        if(theSender == humiture)
//        {
//            humiture->recvResult(errStr);
//        }
    }
    else
    {
        QWidget* theSender = (QWidget*)sender();


//        if(theSender == humiture)
//        {
//            qDebug()<<"send"<<humiture->sendBuf.toHex();
//            sendData(humiture->sendBuf);
//        }
    }
}

MainWindow::~MainWindow()
{
}
void MainWindow::toUpdate()
{
    QString sfile;
    QString dfile;
    QDir dir;

#ifndef i386
    sfile=tr("/udisk/pcaptest");
    dfile=tr("/opt/myapp/pcaptest");
#else
    sfile=tr("./udisk/pcaptest");
    dfile=tr("./opt/myapp/pcaptest");
#endif

    if (!QFile::exists(sfile))
    {
        QString s=tr("找不到更新文件:");
        s+=sfile;
        QMessageBox::information(NULL,tr("错误"),s);
//        QMessageBox::ShowMessageBoxError(s);
        return;
    }
    QDir *createfile = new QDir;
    bool exist = createfile->exists(dfile);
    if (exist)
    {
        createfile->remove(dfile);
    }
    if(!QFile::copy(sfile, dfile))
    {
        QMessageBox::information(NULL,tr("错误"),tr("更新文件出错!"));
//        QMessageBox::ShowMessageBoxError(tr("更新文件出错!"));
        return;
    }
    QMessageBox::information(NULL,tr("更新文件"),tr("更新文件成功,请重新启动程序！"));
//    myHelper::ShowMessageBoxError(tr("更新文件成功,请重新启动程!"));
}

